let winResize = [];
let winRefresh = [];
let winOnload = [];

window.onresize = function () {
  winResize.forEach((fun) => fun());
};

window.onload = function () {
  winOnload.forEach((fun) => fun());
};

window.addEventListener(
  "beforeunload",
  () => {
    winRefresh.forEach((fun) => fun());
  },
  false
);

function addWinResize(fun) {
  winResize.push(fun);
}

function addWinRefresh(fun) {
  winRefresh.push(fun);
}

function addWinOnload(fun) {
  winOnload.push(fun);
}

/**
 * 判断dom元素是否存在于某个dom节点下面(默认是否存在dom树当中)
 */
function exist(dom, parent = document.body) {
  if (!dom || !parent) {
    return false;
  }
  let parentNode = dom;
  while ((parentNode = parentNode.parentNode)) {
    if (parent === parentNode) {
      return true;
    }
  }
  return false;
}

/**
 * 当元素被销毁时触发
 * @param {检查元素} dom
 * @param {检查范围元素} parent
 * @returns Promise
 */
function onDestoryExist(dom, parent = document.body) {
  return new Promise((resolve) => {
    setInterval(() => {
      if (!exist(dom, parent)) {
        resolve();
      }
    });
  });
}

/**
 * 滚动到头部
 */
const scrollTop = () => {
  const timeTop = setInterval(() => {
    // 去控制他的滑行距离
    document.documentElement.scrollTop = scrollTopH.value -= 50;
    // 当滑到顶部的时候记得清除计时器(*) 重点
    if (scrollTopH.value <= 0) {
      clearInterval(timeTop);
    }
  }, 10);
};

/**
 * 禁用浏览器的 ctrl + s
 */
document.onkeydown = function () {
  // 判断 Ctrl+S
  if (event.ctrlKey == true && event.keyCode == 83) {
    // 或者 return false;
    event.preventDefault();
  }
};

const toolWin = {
  addWinResize,
  addWinRefresh,
  addWinOnload,
  exist,
  onDestoryExist,
};

export default toolWin;
